/**
 * 
 */
package com.snsoft.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.snsoft.bean.UserInfo;
import com.snsoft.util.Constants;
import com.snsoft.util.JsonUtils;

/**
 * @author 苏国启
 * 
 * @date 2017年11月18日 下午6:59:52
 * 
 * @Description TODO 判断登录过滤，以及method是否为空过滤, 并对duty和manage请求的用户身份过滤
 * 
 */
@WebFilter(urlPatterns = { "/duty", "/manage", "/environment" })
public class F1_LoginFilter implements Filter {

	@Override
	public void init(FilterConfig fconfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String method = request.getParameter("method");
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		if (method == null || method.trim().length() <= 0) {
			
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
			return;
		} else if (session == null || session.getAttribute("userInfo") == null) {
			response.getWriter()
					.write(JsonUtils.objectToJson(null, Constants.CODE_NOT_LOGIN, Constants.JSON_NOT_LOGIN));
			return;
		} else {
			String url = ((HttpServletRequest) request).getRequestURI();
			int role = ((UserInfo) session.getAttribute("userInfo")).getRole();
			String servlet = url.substring(url.lastIndexOf("/") + 1, url.length());
			// 根据请求的url进行不同的过滤，只对duty、manage的请求进行身份判断
			if ("duty".equals(servlet)) {
				if (role != 1 && role != 2) {
					response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "权限不足, 无法操作！"));
					return;
				} else {
					chain.doFilter(request, response);
				}
			} else if ("manage".equals(servlet)) {
				if (role != 1) {
					response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "权限不足, 无法操作！"));
					return;
				} else {
					chain.doFilter(request, response);
				}
			} else if ("environment".equals(servlet)) {
				chain.doFilter(request, response);
			} else {
				response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
				return;
			}
		}
	}

	@Override
	public void destroy() {

	}

}
